package cl.extractor;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;

import cl.model.dto.Vehicle;
import cl.parsers.Parser;
import cl.parsers.ParserVehicle;

public class VehicleExtractor implements Extractor {

	public Vehicle extract(String url, Vehicle vehicle) {
	
	//	Vehicle vehicle = null; 
		String salidaXML = new String();	
		HttpClient client = new HttpClient( );
		HttpMethod method = new GetMethod( url );

		try {
		    client.executeMethod( method );
		    if( method.getStatusCode( ) == HttpStatus.SC_OK ) {
		        salidaXML = method.getResponseBodyAsString( );
		        System.out.println( salidaXML );
		    }
		} catch( HttpException he ) {
		    System.out.println( "HTTP Problem: " + he.getMessage( ) );
		} catch( IOException ioe ) {
		    System.out.println( "IO Exeception: " + ioe.getMessage( ) );
		} finally {
		    method.releaseConnection( );
		    method.recycle( );
		}	
		
		int tablaPrincipal = salidaXML.indexOf("class='X3'");
		
		if(tablaPrincipal != -1){

			int indiceTablaPrincipal = tablaPrincipal - 18;
			int indiceFinalTablaPrincipal = salidaXML.indexOf("</table>",indiceTablaPrincipal);
			
			String salidaPrimerCorte = "";
			salidaPrimerCorte=salidaXML.substring(indiceTablaPrincipal,indiceFinalTablaPrincipal);
			System.out.println(salidaPrimerCorte);
			
			String[] listadoTR = salidaPrimerCorte.split("</tr>");
			Parser parseVehicle = new ParserVehicle();
			
			 vehicle = parseVehicle.parse(listadoTR, vehicle);
		}
		else{
		System.out.println("ERROR : No se encontro Vehiculo");
		}
		return vehicle;
	}
}
